import React, { PureComponent } from 'react';
import { connect } from 'dva';
import styles from './UsermanageList.less';
import PageHeaderLayout from '../layouts/PageHeaderLayout';
import { Row, Col, Card, Form, Icon, Button, Modal, Divider, Table, Input,message ,Select} from 'antd';
import StandardTable from '../components/StandardTable';
const FormItem = Form.Item;
const Option = Select.Option;
var dispatch;

const userType = {
  '产品':'1',
  '开发':'2',
  '测试':'3',
  '管理员':'4'
}
const CreateForm = Form.create()(props => {
  const { modalVisible, form, roleId, handleModalVisible,modalType,userName,password,realName,roleName,mobile,email,id,handeleKayUpdataUserInfo } = props;
  const okHandle = () => {
    if (modalType === 'add') {

      form.validateFields((err, fieldsValue) => {
        if (err) return;
        form.resetFields();
        fieldsValue.roleId = userType[fieldsValue.roleId];
        dispatch({

          type: 'umodels/fetchUserAdd',
          payload: fieldsValue,
        });
      });

    } else if (modalType === 'edit') {

      form.validateFields(['roleName', 'roleId', 'password', 'mobile', 'email'], (err, fieldsValue) => {
        if (err) return;
        form.resetFields();
        handeleKayUpdataUserInfo(fieldsValue)
      })
    }
  };

  return (
    <Modal
      title={modalType === 'add' ? '创建用户': '修改用户'}
      visible={modalVisible}
       okText={'提交'}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false, form)}
    >
      {modalType === 'add' ? 
        <Form>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="账号">
                  {form.getFieldDecorator('userName', {
                  rules: [{ required: true, message: '用户名正则，4到16位（字母，数字，下划线，减号）', pattern:new RegExp("^[a-zA-Z0-9_-]{4,16}$"), whitespace:true}],
                  initialValue: userName
                  })(<Input placeholder="请输入账号名称"   />)}
                </FormItem>
                <FormItem  labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
                  {form.getFieldDecorator('password', { 
                  rules: [ {required: true, message: '必须且只含有数字和字母，6-10位',pattern:new RegExp("^[a-zA-Z0-9]{3,10}$") }],
                  initialValue: password
                  })(<Input placeholder="请输入密码" />)}
                </FormItem>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="姓名">
                  {form.getFieldDecorator('realName', {
                  rules: [{ required: true, message: '请输入合法姓名',min: 1 ,max:10,whitespace:true }],
                  // initialValue: realName
                  })(<Input placeholder="请输入合法姓名" />)}
                </FormItem>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="角色">
                    {form.getFieldDecorator('roleId', {
                      rules: [{ required: true, message: '请输入角色' }],
                      initialValue: ''
                    })          
                    (<Select style={{ width: 295 }} >
                      <Option value="产品">产品</Option>
                      <Option value="开发">开发</Option>
                      <Option value="测试">测试</Option>
                      <Option value="管理员">管理员</Option>

                    </Select>)}
                 </FormItem>
         <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="联系电话">
              {form.getFieldDecorator('mobile', {
              rules: [{ required: false, message: '请输正确的电话' , len:11}],
              initialValue: mobile
              })(<Input placeholder="请输入联系电话" />)}
         </FormItem>

         <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="电子邮箱">
              {form.getFieldDecorator('email', {
              rules: [{ required: false, message: '请输入正确的电子邮箱格式',pattern:new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$") } ],
                initialValue: email
              })(<Input placeholder="请输入电子邮箱" />)}
          </FormItem>
        </Form>:null
      }

      {modalType==='edit' ?
      <Form>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="所属角色">
              {form.getFieldDecorator('roleId', {
                rules: [{ required: false, message: '请输入角色' }],
                initialValue: roleName
              })          
              (<Select style={{ width: 295 }} >
                <Option value="产品">产品</Option>
                <Option value="开发">开发</Option>
                <Option value="测试">测试</Option>
                <Option value="管理员">管理员</Option>

              </Select>)}
         </FormItem>

          <FormItem  labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="修改密码">
            {form.getFieldDecorator('password', { 
              rules: [ {required: false,message: '必须且只含有数字和字母，6-10位',pattern:new RegExp("^[a-zA-Z0-9]{3,10}$")}],
              
          })(<Input placeholder="请输入新密码" />)}
          </FormItem>

         <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="联系电话">
      {form.getFieldDecorator('mobile', {
      rules: [{ required: false, message: '请输正确的电话' , len:11 }],
      initialValue: mobile
      })(<Input placeholder="请输入联系电话" />)}
      </FormItem>

     <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="电子邮箱">
        {form.getFieldDecorator('email', {
          rules: [{ required: false, message: '请输入正确的电子邮箱格式',pattern:new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$") } ],
          initialValue: email
        })(<Input placeholder="请输入电子邮箱" />)}
      </FormItem>
      </Form>
      :null}
    </Modal>
  );
});








@connect(({ umodels, loading }) => ({
  umodels,
  loading,
}))
export default class UserManageList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentId: null
    };
  }

  componentDidMount() {
    dispatch  = this.props.dispatch;
    this.props.dispatch({
      type: 'umodels/fetchGetUserList',
      payload:{}
    });
  }

  componentWillReceiveProps(nextPros){
      if(this.props.umodels.isShowMessage !== nextPros.umodels.isShowMessage && nextPros.umodels.isShowMessage === true){
        this.showMesage(nextPros.umodels.messagetips, nextPros.umodels.message, nextPros.umodels.duration)
      }
  }

  showMesage(type,message,duration = 2){
    switch(type){
          case 'success':
          message.success(message,duration);
          break;
          case 'info':
          message.info(message,duration);
          break;
          case 'warning':
          message.warning(message,duration);
          break;
          case 'error':
          message.error(message,duration);
          break;
    }
    this.props.dispatch({
      type: 'umodels/showMessage',
      payload:{  isShowMessage: false }
    });
}

  createUser(){
    this.props.dispatch({
      type: 'umodels/clearUserForm',
    });
    this.handleModalVisible(true);
  }

  handleModalVisible = (flag, form) => {
    form&&form.resetFields();

    this.props.dispatch({
      type: 'umodels/changeUserForm',
      payload:{  modalVisible: flag }
    });
  };

  handleDeleteKey=(ida)=>{
    this.props.dispatch({
      type: 'umodels/fetchUserDeleteKey',
      payload:{id:ida}
    });
  }

  handeleGetUserInfoKay=(record,flag=true)=>{
   
    this.props.dispatch({
      type: 'umodels/changeUserForm',
      payload: {
        modalVisible: true,
        modalType: 'edit',
        //  userName: record.userName,
        realName: record.realName,
        roleId: record.roleId,
        roleName: record.roleName,
        mobile: record.mobile,
        email: record.email
      }
    });   
 }
  handeleKayUpdataUserInfo = (fieldsValue) => {
    fieldsValue.id = this.state.currentId
    fieldsValue.roleId = userType[fieldsValue.roleId];
    this.props.dispatch({
      type: 'umodels/fetchUserUpdataKey',
      payload: fieldsValue
    })
  };

  render() {
    const { modalVisible } = this.state;
    const { umodels } = this.props;
    const { data,messagetips } = umodels;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handeleKayUpdataUserInfo:this.handeleKayUpdataUserInfo,
      ...umodels
    };

    const columns = [
      {
        title: '账号',
        dataIndex: 'userName',
        key: 'userName',  //userName
        render: text => (
          <a href="javascript:;" onClick={() => {}}>
            {text}
          </a>
        ),
      },
      {
        title: '姓名',
        dataIndex: 'realName',
         key: 'realName', //realName
      },
      {
        title: '角色',
        dataIndex: 'roleName', //role
        key: 'roleName', //roleName
      },
      {
        title: '手机',
        dataIndex: 'mobile', //mobile
        key: 'mobile', //mobile
      },
      {
        title: '邮箱',
        dataIndex: 'email', //email
        key: 'email', //email
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:;" onClick={() =>{
              this.setState({currentId: record.id})
              this.handeleGetUserInfoKay(record);
            }}>
              修改
            </a>
            <Divider type="vertical" />
            <a href="javascript:;"onClick={()=>this.handleDeleteKey(record.id)}>删除</a>
          </span>
        ),
      },
    ];

    
    return (
      <PageHeaderLayout>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}> </div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.createUser()}>
              创建用户
            </Button>
          </div>
          <Card>
            <Table dataSource={data} columns={columns}/>
          </Card>
          <CreateForm {...parentMethods} />      
        </div>
      </PageHeaderLayout>
    );
  }
}


